package niuke;

import java.util.Arrays;

/**
 * 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],
 * 其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
 */
public class MutiplyLackOne {
    /**
     * 上三角 * 下三角
     *
     * @param A
     * @return
     */
    public static int[] multiplyShuoGG(int[] A) {
        int n = A.length;
        int[] rear = new int[n];
        int[] head = new int[n];
        rear[n - 1] = 1;
        for (int i = n - 2; i >= 0; i--) {
            rear[i] = rear[i + 1] * A[i + 1];
        }
        head[0] = 1;
        for (int i = 2; i <= n; i++) {
            head[i - 1] = head[i - 2] * A[i - 2];
        }
        for (int i = 0; i < n; i++) {
            rear[i] = rear[i] * head[i];
        }
        return rear;
    }

    /**
     * 思路和上面一样, 少用了1个数组
     *
     * @param A
     * @return
     */
    public static int[] multiplyAnswer(int[] A) {
        int n = A.length;
        int[] rear = new int[n];
        rear[n - 1] = 1;
        for (int i = n - 2; i >= 0; i--) {
            rear[i] = rear[i + 1] * A[i + 1];
        }
        int temp = 1;
        rear[0] = 1 * rear[0];
        for (int i = 1; i < n; i++) {
            temp = temp * A[i - 1];
            rear[i] = rear[i] * temp;
        }
        return rear;
    }

    public static void main(String[] args) {
        int[] test = {1, 2, 3, 4, 5};
        System.out.println(Arrays.toString(multiplyAnswer(test)));
        System.out.println(Arrays.toString(multiplyShuoGG(test)));
    }
}
